<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use Exception;
use think\Db;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 专家管理
 *
 * @icon fa fa-circle-o
 */
class Expert extends Backend
{

    protected $noNeedRight = ['searchProfessional', 'import'];
    /**
     * Expert模型对象
     * @var \app\admin\model\Expert
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Expert;

        $pid = Db::name('dictionary')->where('code', 10000)->where('status', 1)->value('id');
        $professional = Db::name('dictionary')->where('pid', $pid)->where('status', 1)->select();
        foreach ($professional as $k => $v) {
            $professional[$k]['name'] = $v['title'];
            $professional[$k]['id'] = $v['title'];
        }
        $this->view->assign('professional', $professional);

        $pid1 = Db::name('dictionary')->where('code', 10001)->where('status', 1)->value('id');
        $position = Db::name('dictionary')->where('pid', $pid1)->where('status', 1)->select();
        foreach ($position as $k => $v) {
            $position[$k]['name'] = $v['title'];
            $position[$k]['id'] = $v['title'];
        }
        $this->view->assign('position', $position);

        $pid2 = Db::name('dictionary')->where('code', 10002)->where('status', 1)->value('id');
        $expert_data = Db::name('dictionary')->where('pid', $pid2)->where('status', 1)->select();
        foreach ($expert_data as $k => $v) {
            $expert_data[$k]['name'] = $v['title'];
            $expert_data[$k]['id'] = $v['title'];
        }
        $this->view->assign('expert_data', $expert_data);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index($ids = '')
    {

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            $this->view->assign('project_id', $ids);
            $expert_ids = '';
            if ($ids) {
                $expert_ids = Db::name('project')->where('id', $ids)->value('expert_ids');
            }
            $this->view->assign('expert_ids', $expert_ids);
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        $filter = json_decode($this->request->get("filter"), true);
        $op     = json_decode($this->request->get("op"), true);

        if (isset($filter['province'])) {
            $province = $filter['province'];
            unset($filter['province'], $op['province']);
            $filter['province'] =  $province;
            $op['province']     = '=';
            $this->request->get(["filter" => json_encode($filter), 'op' => json_encode($op)]);
        }

        if (isset($filter['city'])) {
            $city = $filter['city'];
            unset($filter['city'], $op['city']);
            $filter['city'] = $city;
            $op['city']     = '=';
            $this->request->get(["filter" => json_encode($filter), 'op' => json_encode($op)]);
        }

        if (isset($filter['area'])) {
            $area = $filter['area'];
            unset($filter['area'], $op['area']);
            $filter['area'] = $area;
            $op['area']     = '=';
            $this->request->get(["filter" => json_encode($filter), 'op' => json_encode($op)]);
        }

        [$where, $sort, $order, $offset, $limit] = $this->buildparams();

        // var_dump($where);exit;
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

        $page = $list->currentPage();
        $total = $list->total();
        $pageSize = $list->listRows();
        $startIndex = ($page - 1) * $pageSize + 1; // 计算起始序号
        $endIndex = $startIndex + $pageSize - 1; // 计算结束序号
        $endIndex = $endIndex > $total ? $total : $endIndex; // 确保序号不超过总记录数
        foreach ($list->items() as $key => $item) {
            $list->items()[$key]['rownum'] = $startIndex + $key; // 添加序号字段
        }

        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        $params['professional'] = implode(',', $params['professional']);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function searchProfessional()
    {
        $pid = Db::name('dictionary')->where('code', 10000)->where('status', 1)->value('id');

        $keyworld = $this->request->post('name');
        $pageNumber = $this->request->post('pageNumber');

        if ($this->request->request("keyValue")) {
            return [
                'total' => 1,
                'list' => [
                    ['id' => $this->request->request("keyValue"), 'name' => $this->request->request("keyValue")]
                ]
            ];
        }
        if ($keyworld) {
            $professional = Db::name('dictionary')->where('pid', $pid)->where('title', 'like', '%' . $keyworld . '%')->where('status', 1)->paginate(['list_rows' => 10, 'page' => $pageNumber]);
        } else {
            $professional = Db::name('dictionary')->where('pid', $pid)->where('status', 1)->paginate(['list_rows' => 10, 'page' => $pageNumber]);
        }
        $data = $professional->items();
        foreach ($data as $k => $v) {
            $data[$k]['name'] = $v['title'];
            $data[$k]['id'] = $v['title'];
        }
        return json(['list' => $data, 'total' => $professional->total()]);
    }
    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $params['professional'] = implode(',', $params['professional']);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function import()
    {
        // 完全自定义导入逻辑
        if ($this->request->isPost()) {
            // 处理文件上传和数据插入...
            $this->success('导入成功');
        }
        return $this->fetch();
    }

    /**
     * 导入excel
     */
    public function import_excel()
    {
        $file = request()->file('file');
        if (!$file) {
            $this->error('请选择文件');
        }
        // 验证文件格式
        $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);
        if (!in_array($ext, ['xls', 'xlsx'])) {
            $this->error('仅支持 Excel 文件');
        }
        // 读取 Excel
        $spreadsheet = IOFactory::load($file->getRealPath());
        $sheet = $spreadsheet->getActiveSheet();
        $rows = $sheet->toArray();
        // 去除表头
        array_shift($rows);
        array_shift($rows);
        // 遍历数据并插入数据库
        $success = 0;
        $error = 0;
        foreach ($rows as $row) {
            // 数据验证（示例）
            if (empty($row[0]) || empty($row[1])) {
                $error++;
                continue;
            }
            $address = $row[7];
            $address_array = explode('-', $address);
            // 构造数据
            $data = [
                'name' => $row[0],
                'sex' => $row[1] == '男' ? 1 : 2,
                'position' => $row[2],
                'professional' => $row[3],
                'work_unit' => $row[4],
                'expert_data' => $row[5],
                'contact_tel' => $row[6],
                'province' => $address_array[0],
                'city' => $address_array[1],
                'area' => $address_array[2],
                'createtime' => time(),
                'updatetime' => time()
            ];
            $isexit = Db::name('expert')->where(['name' => $data['name'], 'contact_tel' => $data['contact_tel']])->where('deletetime', null)->find();
            if (empty($isexit)) {
                try {
                    // $this->model->save($data);
                    Db::name('expert')->insert($data);
                    $success++;
                } catch (\Exception $e) {
                    $error++;
                }
            } else {
                $error++;
            }
        }
        $this->success("导入完成：成功 {$success} 条，失败 {$error} 条", '#');
    }
}
